﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using FastReflectionLib;
using System.Web;
using Newtonsoft.Json;
using System.Data;
using Newtonsoft.Json.Linq;
using SZHL.Data;
using SZHL.UI.AppCode;
using Senparc.Weixin.QY.Entities;

namespace SZHL.UI.API
{
    public class QYGGManage : IWsService
    {
        public void ProcessRequest(HttpContext context, ref Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            MethodInfo methodInfo = typeof(QYGGManage).GetMethod(msg.Action.ToUpper());
            QYGGManage model = new QYGGManage();
            methodInfo.FastInvoke(model, new object[] { context, msg, P1, P2, UserInfo });


        }
        #region 公告管理

        /// <summary>
        /// 添加公告
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void ADDQYGG(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            ZH_XTGG xtgg = JsonConvert.DeserializeObject<ZH_XTGG>(P1);
            if (xtgg.GGTitle.Trim() == "")
            {
                msg.ErrorMsg = "标题不能为空";
                return;
            }
            if (xtgg.GGContent.Trim() == "")
            {
                msg.ErrorMsg = "公告内容不能为空";
                return;
            }
            if (xtgg.ID == 0)
            {
                xtgg.CRDate = DateTime.Now;
                xtgg.FBTime = DateTime.Now;
                xtgg.CRUser = UserInfo.User.UserName;
                xtgg.BZDanWei = new JH_Auth_BranchB().GetBranchNameByCode(UserInfo.User.BranchCode);
                xtgg.CRUserName = UserInfo.User.UserRealName;
                new ZH_XTGGB().Insert(xtgg);

                FT_File File = new FT_File();
                if (!string.IsNullOrEmpty(xtgg.remark1))
                {
                    File = new FT_FileB().GetEntity(d => d.ID.ToString() == xtgg.remark1.Split(',')[0].ToString());
                }
                //发送消息
                Article ar = new Article();
                ar.Title = xtgg.GGTitle;
                ar.Description = xtgg.GGTitle;
                if (File != null && (File.FileExtendName == "jpg" || File.FileExtendName == "png"))
                {
                    ar.PicUrl = UserInfo.QYinfo.FileServerUrl + "/image/" + File.FileMD5;
                }
                WXHelp.SendTH(ar, "qygg", xtgg.ID, xtgg.JSUser);

            }
            else
            {
                new ZH_XTGGB().Update(xtgg);
            }
            msg.Result = xtgg;
        }
        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg">公告类型</param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETUSERQYGGLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strWhere = string.Format("  (','+JSUser+','  like '%," + UserInfo.User.UserName + ",%' or JSUser='' )");
            if (P1 != "")
            {
                strWhere += string.Format(" And   remark='{0}'", P1);
            }
            string content = context.Request.QueryString["content"] ?? "";
            if (content != "")
            {
                strWhere += string.Format(" And   GGTitle like '%{0}%'", content);
            }
            int page = 0;
            int.TryParse(P2, out page);
            page = page == 0 ? 1 : page;
            int total = 0;
            DataTable dt = new ZH_XTGGB().GetDataPager("ZH_XTGG", "ID,GGTitle,GGContent,CRUserName,ReadUser,CRDate,remark,Files,FBTime,CRUser ", 8, page, "CRDate desc", strWhere, ref total);
            string Ids = "";
            string fileIDs = "";
            foreach (DataRow row in dt.Rows)
            {
                Ids += row["ID"].ToString() + ",";
                if (!string.IsNullOrEmpty(row["Files"].ToString()))
                {
                    fileIDs += row["Files"].ToString() + ",";
                }
            }
            Ids = Ids.TrimEnd(',');
            fileIDs = fileIDs.TrimEnd(',');
            if (Ids != "")
            {
                DataTable dtPL = new JH_Auth_TLB().GetDTByCommand(string.Format("SELECT ID,MSGTLYID,MSGType,MSGContent,CRDate,CRUser,CRUserName  FROM JH_Auth_TL WHERE MSGType='QYGG' AND  MSGTLYID in ({0})", Ids));
                List<FT_File> FileList = new FT_FileB().GetEntities(d => fileIDs.Split(',').Contains(d.ID.ToString())).ToList();

                dt.Columns.Add("PLList", Type.GetType("System.Object"));
                dt.Columns.Add("FileList", Type.GetType("System.Object"));
                foreach (DataRow row in dt.Rows)
                {
                    row["PLList"] = dtPL.FilterTable("MSGTLYID=" + row["ID"]);
                    if (FileList.Count > 0)
                    {

                        string[] fileIds = row["Files"].ToString().Split(',');
                        row["FileList"] = FileList.Where(d => fileIds.Contains(d.ID.ToString())).ToList();
                    }
                    else
                    {
                        row["FileList"] = "[]";
                    }
                }
            }
            msg.Result = dt;
            msg.Result1 = total;

        }
        public void GETQYGGINFOLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            ZH_XTGG gg = new ZH_XTGGB().GetEntity(d => d.ID.ToString() == P1);
            if (!string.IsNullOrEmpty(P1))
            {
                string[] fileIds = gg.Files.Split(',');
                msg.Result = new FT_FileB().GetEntities(d => fileIds.Contains(d.ID.ToString()));
            }
            msg.Result1 = new ZH_RCTXB().GetDTByCommand("  SELECT ID,MSGTLYID,MSGType,MSGContent,CRDate,CRUser,CRUserName  FROM JH_Auth_TL WHERE MSGType='" + P2 + "' AND  MSGTLYID='" + gg.ID + "'");
        }
        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">公告类型</param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETQYGGLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strWhere = "";
            if (P1 != "")
            {
                strWhere = string.Format(" And   remark='{0}'", P1);
            }
            string content = context.Request.QueryString["content"] ?? "";
            if (content != "")
            {
                strWhere += string.Format(" And   GGTitle like '%{0}%'", content);
            }
            string strSQL = string.Format(@"select  ID,GGTitle,GGContent,CRUserName,ReadUser,CRDate,remark from ZH_XTGG  where 1=1  {0}   order by CRDate desc  ", strWhere);
            DataTable dt = new ZH_XTGGB().GetDTByCommand(strSQL);
            dt.Columns.Add("UserCount");
            foreach (DataRow row in dt.Rows)
            {
                row["UserCount"] = row["ReadUser"].ToString() == "" ? 0 : row["ReadUser"].ToString().Split(',').Length;
            }
            msg.Result = dt;

        }
        /// <summary>
        /// 获取公告列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">公告类型</param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETQYGGLIST_PAGE(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strWhere = string.Format("  ','+JSUser+','  like '%," + UserInfo.User.UserName + ",%'  or JSUser=''");
            if (P1 != "")
            {
                strWhere = string.Format(" And   remark='{0}'", P1);
            }
            string content = context.Request.QueryString["content"] ?? "";
            if (content != "")
            {
                strWhere += string.Format(" And   GGTitle like '%{0}%'", content);
            }
            int page = 1;
            if (P2 != "")
            {
                page = Int32.Parse(P2);
            }
            //string strSQL = string.Format(@"select  ID,GGTitle,GGContent,CRUserName,ReadUser,CRDate,remark from ZH_XTGG  where 1=1  {0}    ", strWhere);
            int total = 0;
            DataTable dt = new ZH_XTGGB().GetDataPager("ZH_XTGG", "ID,GGTitle,GGContent,CRUserName,ReadUser,CRDate,remark ", 8, page, "CRDate desc", strWhere, ref total);
            dt.Columns.Add("UserCount");
            foreach (DataRow row in dt.Rows)
            {
                row["UserCount"] = row["ReadUser"].ToString() == "" ? 0 : row["ReadUser"].ToString().Split(',').Length;
            }
            msg.Result = dt;

        }
        /// <summary>
        /// 获取公告信息
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETQYGGMODEL(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            ZH_XTGG xtgg = new ZH_XTGGB().GetEntity(d => d.ID.ToString() == P1);
            msg.Result = xtgg;
            msg.Result1 = new ZH_RCTXB().GetDTByCommand("  SELECT ID,MSGTLYID,MSGType,MSGContent,CRDate,CRUser,CRUserName  FROM JH_Auth_TL WHERE MSGType='QYGG' AND  MSGTLYID='" + P1 + "'");
            msg.Result2 = new FT_FileB().GetEntities(d => xtgg.Files.Split(',').Contains(d.ID.ToString()));
        }
        public void UPDATEQYGGREADUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            ZH_XTGG xtgg = new ZH_XTGGB().GetEntity(d => d.ID.ToString() == P1);
            if (xtgg.ReadUser == null || !xtgg.ReadUser.Split(',').Contains(UserInfo.User.UserName))
            {
                xtgg.ReadUser += (xtgg.ReadUser == "" || xtgg.ReadUser == null ? "" : ",") + UserInfo.User.UserName;
                new ZH_XTGGB().Update(xtgg);
            }
        }


        /// <summary>
        /// 获取已阅人，及人数
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETREADUSER(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strSql = string.Format(@"select stuff((select ','+UserRealName from JH_Auth_ConFirmData 
                                            inner join JH_Auth_User on CRUser=UserName 
                                            where FormCode='{0}' and FormID={1}
                                            for xml path('')),1,1,'') as UserName,Count(0)  UserCount
                                            from JH_Auth_ConFirmData where FormCode='{0}'  and FormID={1}", P1, P2);
            msg.Result = new JH_Auth_ConFirmDataB().GetDTByCommand(strSql);
        }
        /// <summary>
        /// 添加评论
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="strParamData"></param>
        /// <param name="strUserName"></param>
        public void ADDCOMENT(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strMsgType = context.Request["MsgType"] ?? "";
            string strMsgLYID = context.Request["MsgLYID"] ?? "";
            string strPoints = context.Request["Points"] ?? "0";

            JH_Auth_TL Model = new JH_Auth_TL();
            Model.CRDate = DateTime.Now;
            Model.CRUser = UserInfo.User.UserName;
            Model.CRUserName = UserInfo.User.UserRealName;
            Model.MSGContent = P1;
            Model.MSGTLYID = strMsgLYID;
            Model.MSGType = strMsgType;
            int pt = Int32.Parse(strPoints);
            Model.Points = pt;
            new JH_Auth_TLB().Insert(Model);
            if (Model.MSGType == "GZRZ")
            {
                ZH_GZRZ gzrz = new ZH_GZRZB().GetEntity(d => d.ID.ToString() == Model.MSGTLYID);
                if (gzrz.CRUser != UserInfo.User.UserName)
                {
                    //发送消息
                    string content = UserInfo.User.UserRealName + "评论了" + gzrz.CRDate.Value.ToString("yyyy-MM-dd") + "的" + gzrz.LeiBie + "内容";
                    new JH_Auth_User_CenterB().SendMsg(UserInfo, "gzrb", "工作日报评论", content, gzrz.ID, gzrz.CRUser);
                }
            }


            msg.Result = Model;

        }
        public void DELQYGGBYID(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {

                if (new ZH_XTGGB().Delete(d => d.ID.ToString() == P1))
                {
                    if (new JH_Auth_TLB().Delete(d => d.MSGTLYID == P1 && d.MSGType == "QYGG"))
                    {
                        msg.ErrorMsg = "";
                    }
                }
            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }
        #endregion

        #region 字典添加编辑6、公告栏目 7、公告类型

        /// <summary>
        /// 获取栏目列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETCOLUMNLIST(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string tableName = "";
            string strColumn = "";
            if (P1 == "6")
            {
                tableName = "LEFT join ZH_XTGG  xt on   zd.TypeNo=xt.Remark ";
            }
            else if (P1 == "7")
            {
                tableName = "LEFT join ZH_GZRZ  xt on   zd.TypeNo=xt.Remark ";
                if (UserInfo.User.UserName != "")
                {
                    tableName += string.Format(" And  xt.CRUser='{0}'", UserInfo.User.UserName);
                }

            }
            //else if (P1 == "10")
            //{
            //    strColumn = ",xt.ProcessDefinitionID";
            //    tableName = "LEFT join Yan_WF_PD  xt on   zd.TypeNo=xt.ProcessName ";
            //}
            string strSQL = string.Format(@"select zd.ID,zd.TypeNO,zd.TypeName {0}  from  JH_Auth_ZiDian zd {1}
                               where TypeName='Y' And  Class={2} group by zd.TypeNO,zd.ID,zd.TypeName{0}", strColumn, tableName, P1);
            DataTable dt = new JH_Auth_ZiDianB().GetDTByCommand(strSQL);

            msg.Result = dt;
            if (P1 == "7" || P1 == "8" || P1 == "3")
            {
                DataTable dtBranch = new JH_Auth_BranchB().GetBranchListByCode(1);
                msg.Result1 = dtBranch;
            }
        }
        /// <summary>
        /// 获取栏目设置列表
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETCOLUMNDATA(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string tableName = "";
            string strColumn = "";
            if (P1 == "6")
            {
                tableName = "LEFT join ZH_XTGG  xt on   zd.TypeNo=xt.Remark ";
            }
            else if (P1 == "7")
            {
                tableName = "LEFT join ZH_GZRZ  xt on   zd.TypeNo=xt.Remark ";
                if (UserInfo.User.UserName != "")
                {
                    tableName += string.Format(" And  xt.CRUser='{0}'", UserInfo.User.UserName);
                }

            }
            string strSQL = string.Format(@"select zd.ID,zd.TypeNO,zd.TypeName {0}  from  JH_Auth_ZiDian zd {1}
                               where  Class={2} group by zd.TypeNO,zd.ID,zd.TypeName{0}", strColumn, tableName, P1);
            DataTable dt = new JH_Auth_ZiDianB().GetDTByCommand(strSQL);
            msg.Result = dt;

        }
        /// <summary>
        /// 添加或修改栏目
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void MODIFYCOLUMN(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            JH_Auth_ZiDian column = JsonConvert.DeserializeObject<JH_Auth_ZiDian>(P1);
            if (column.TypeNO.Trim() == "")
            {
                msg.ErrorMsg = "栏目名称不能为空";
            }
            else
            {
                if (column.ID != 0)
                {
                    new JH_Auth_ZiDianB().Update(column);
                }
                else
                {
                    JH_Auth_ZiDian column1 = new JH_Auth_ZiDianB().GetEntity(d => d.TypeNO == column.TypeNO && d.Class == column.Class);
                    if (column1 != null)
                    {
                        msg.ErrorMsg = "该栏目已存在";
                    }
                    else
                    {
                        column.TypeName = "Y";
                        new JH_Auth_ZiDianB().Insert(column); 
                    }
                }
            }
            msg.Result = column;
        }

        /// <summary>
        /// 获取栏目
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">Id</param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void GETCOLUMNBYID(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            msg.Result = new JH_Auth_ZiDianB().GetEntity(d => d.ID.ToString() == P1 && d.Class.ToString() == P2);
        }
        /// <summary>
        /// 删除栏目
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void DELCOLUMNBYID(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            if (!new JH_Auth_ZiDianB().Delete(d => d.ID.ToString() == P1 && d.Class.ToString() == P2))
            {
                msg.Result = "删除失败";
            }
        }
        /// <summary>
        /// 删除栏目
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="strUserName"></param>
        public void MODIFYZIDIANSTATES(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            string strSql = string.Format(" update JH_Auth_ZiDian set TypeName='{0}' where Id={1}", P1, P2);
            new JH_Auth_ZiDianB().ExsSql(strSql);
             
        }
        #endregion

        #region 首页获取数据
        public void GETUSERINDEXDATA(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            //企业公告
            string strWhere = string.Format("  (','+JSUser+','  like '%," + UserInfo.User.UserName + ",%' or JSUser='' )");
            int page = 1;
            int total = 0;
            DataTable dt = new ZH_XTGGB().GetDataPager("ZH_XTGG", "ID,GGTitle,GGContent,CRUserName,ReadUser,CRDate,remark,Files,FBTime,CRUser ", 3, page, "CRDate desc", strWhere, ref total);
            msg.Result = dt;
            //任务代办
            DataTable dtList = new DataTable();
            string strSql = string.Format("select   *  FROM ZH_RCTX  where (CRUser='{0}' or  ','+RWFZR+','  like '%,{0},%'  or ','+RWCYR+','  like '%,{0},%')And RWStatus=0 ORDER BY LeiBie DESC,CRDate DESC ", UserInfo.User.UserName);
            dtList = new ZH_RCTXB().GetDTByCommand(strSql);
            dtList.Columns.Add("PLList", Type.GetType("System.Object"));
            for (int i = 0; i < dtList.Rows.Count; i++)
            {
                dtList.Rows[i]["PLList"] = new JH_Auth_TLB().GetTL("RCTX", dtList.Rows[i]["ID"].ToString());

            }
            msg.Result1 = dtList;

        }
        /// <summary>
        /// 微信首页数据
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1"></param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void GETWXINDEXDATA(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            //企业公告
            if (P1 == "") { P1 = "5"; }

            DataTable dt = new ZH_XTGGB().GetDTByCommand("select top " + P1 + " * from ZH_XTGG order by crdate desc");
            msg.Result = dt;
            //用户信息

            msg.Result1 = UserInfo;

        }
        #endregion

        #region 评论删除
        /// <summary>
        /// 删除评论
        /// </summary>
        /// <param name="context"></param>
        /// <param name="msg"></param>
        /// <param name="P1">评论Id</param>
        /// <param name="P2"></param>
        /// <param name="UserInfo"></param>
        public void DELTL(HttpContext context, Msg_Result msg, string P1, string P2, JH_Auth_UserB.UserInfo UserInfo)
        {
            try
            {
                if (!new JH_Auth_TLB().Delete(d => d.ID.ToString() == P1))
                {
                    msg.ErrorMsg = "删除失败";
                }

            }
            catch (Exception ex)
            {
                msg.ErrorMsg = ex.Message;
            }
        }
        #endregion


    }
}